/**
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trim.gui.testing.models;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.table.AbstractTableModel;
import trim.Trim;
import trim.gui.testing.PlaginManager;

/**
 *
 * @author Дмитрий
 */
public class PlaginsTableModel extends AbstractTableModel implements ListModel
{

  private PlaginManager plaginManager;
  private int plaginIndex=-1;

  public PlaginsTableModel(PlaginManager plaginManager)
  {
    this.plaginManager=plaginManager;
  }

  public void removePlagin(int i)
  {
    if(i<0)return;
    plaginManager.removePlagin(i);
    plaginIndex=-1;
    fireTableDataChanged();
    fireListDataChanged();
    try
    {
      plaginManager.savePlagins();
    }catch(IOException ex)
    {
      ex.printStackTrace();
    }
  }

  public void setPlaginIndex(int plaginIndex)
  {
    this.plaginIndex=plaginIndex;
    fireTableDataChanged();
  }

  public int getRowCount()
  {
    if(plaginIndex<0)return 0;
    return plaginManager.getPlagin(plaginIndex).getMethodCount();
  }

  @Override
  public String getColumnName(int column)
  {
    switch(column)
    {
      case 3:
        return "Name";
      case 1:
        return "Version";
      case 2:
        return "Description";
      case 0:
        return "Class";
    }
    return "";
  }

  public int getColumnCount()
  {
    return 4;
  }

  public Object getValueAt(int rowIndex,int columnIndex)
  {
    Trim t=plaginManager.getPlagin(plaginIndex).getMethods().get(rowIndex);
    switch(columnIndex)
    {
      case 3:
        return t.getName();
      case 1:
        return t.getVersion();
      case 2:
        return t.getDescription();
      case 0:
        return t.getClass().getCanonicalName();
    }
    return null;
  }

  public int getSize()
  {
    return plaginManager.getPlaginCount();
  }

  public Object getElementAt(int index)
  {
    return plaginManager.getPlaginFile(index).getName();
  }

  public void fireListDataChanged()
  {
    ListDataEvent evt=new ListDataEvent(this,ListDataEvent.CONTENTS_CHANGED,0,getSize());
    for(ListDataListener l:listDataListeners)
      l.contentsChanged(evt);
  }
  List<ListDataListener> listDataListeners=new LinkedList();

  public void addListDataListener(ListDataListener l)
  {
    listDataListeners.add(l);

  }

  public void removeListDataListener(ListDataListener l)
  {
    listDataListeners.remove(l);
  }
}
